import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import SearchBar from './SearchBar';
import './Navbar.css'; 
import { ReactComponent as Menu } from '../assets/icons/menu.svg';
import defaultAvatar from '../assets/images/默认头像.jpg';
import {getMyprofile} from '../api/userApi';

const Navbar = ({ onLogout }) => {
  const [menuOpen, setMenuOpen] = useState(false); // 控制菜单显示的状态
  const navigate = useNavigate(); // 使用 useNavigate 来进行路由跳转
  const dropdownRef = useRef(null); // 创建一个引用用于下拉菜单
  const menuIconRef = useRef(null); // 创建一个引用用于菜单图标
  const [userId, setUserId] = useState(null); // 新增 userId 状态
  const [myProfile, setMyProfile] = useState(null); // 新增 myProfile 状态

  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
    } 

  }, []);

  useEffect(() => {
    // 如果没有 userId 就不执行后续操作
    if (userId) {
     // 获取用户头像
     getMyprofile(userId)
     .then((data) => {
       console.log('User profile data:', data); // 调试输出
       setMyProfile(data);  // 设置获取到的数据
     })
     .catch((error) => {
       console.error('Error fetching my profile:', error);
     });
    }
  }, [userId]);



  const avatarSrc = myProfile?.image ? 'http://localhost:8080/' + myProfile.image : defaultAvatar;

  const handleMenuClick = () => {
    setMenuOpen(prev => !prev); // 切换菜单状态
  };

  const handleSearch = (query) => {
    navigate(`/search?query=${encodeURIComponent(query)}`); // 跳转到 /search 页面并传递 query 参数
  };

  const handleAvatarClick = () => {
    if (userId) {
      navigate(`/personal/${userId}`); // 点击头像时跳转到个人页面，并将 userId 添加到路由中
    }
  };

  const handleLogoutClick = () => {
    onLogout(); // 调用父组件传来的登出函数
    localStorage.removeItem('userId'); // 清除 localStorage 中的 userId
    navigate('/'); // 跳转到登录页面
  };

  useEffect(() => {
    const handleClickOutside = (event) => {
      // 判断点击的目标是否在 dropdownRef 或 menuIconRef 之外
      if (dropdownRef.current && !dropdownRef.current.contains(event.target) && 
          menuIconRef.current && !menuIconRef.current.contains(event.target)) {
        setMenuOpen(false); // 隐藏下拉菜单
      }
    };

    // 监听点击事件
    document.addEventListener('mousedown', handleClickOutside);
    
    return () => {
      // 清除监听
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 在这里处理加载状态显示
  if (!myProfile) {
    return <div>Loading...</div>;
  }

  return (
    <div className="navbar">
      <div className="navbar-logo">
        <h1>Orbitly</h1>
      </div>
      <div className="navbar-menu">
        <button onClick={() => navigate(`/home/${userId}`)}>首页</button>
        <button onClick={() => navigate('/popular')}>热门</button>
      </div>  

      <div className="navbar-search">
        <SearchBar onSearch={handleSearch} /> 
      </div>

      <div className='navbar-avatar'>
        <img
          src={avatarSrc}
          alt="User Avatar"
          onClick={handleAvatarClick}  
        />
      </div>



      <div className="navbar-menu-icon-container" onClick={handleMenuClick} ref={menuIconRef}>
        <Menu className="navbar-menu-icon"/>
      </div>

      {menuOpen && (
        <div className="navbar-dropdown" ref={dropdownRef}>
          <button onClick={() => navigate('/settings')} className="dropdown-item">设置</button>
          <button onClick={handleLogoutClick} className="dropdown-item">登出</button>
        </div>
      )}
    </div>
  );
};

export default Navbar;
